<template>
  <cnlw class="index">
    <!-- 图片包裹视图容器 -->
    <zrf class="animation-image" :class="state" :style="{zIndex:z_state}">
      <!-- 倒影图片 -->
      <image class='top-image' :src="assetsUrl+'static/images/bg_01.jpg'" style=' transform:rotate(180deg);' />
      <!-- 正图 -->
      <image class='bottom-image' :src="assetsUrl+'static/images/bg_02.jpg'" />
    </zrf>
    <!-- 页面内容 -->
    <zrf>
      <div class="bg_music" @tap="audioPlay">
        <image
          :src="assetsUrl+'static/images/music_icon.png'"
          class="musicImg"
          :class="isPlay?'music_icon':''"
        />
        <image
          :src="assetsUrl+'static/images/music_play.png'"
          class="music_play"
          :class="isPlay?'pauseImg':'playImg'"
        />
      </div>
      <audio id="myAudio" :src="audioUrl" autoplay loop></audio>

      <div class="calendar_box" :class="showCalendar?'':'hide_box'">
        <image class="btn" :src="assetsUrl+'static/images/calendar.png'" @tap="switchCalendar" />
        <div class="left" :class="showCalendar?'':'hide_left'">
          <div class="circle">
            <span class="day">{{day}}</span>
            <span class="month">{{month}}月</span>
          </div>
          <div class="addressWeather">
            <p class="address">{{address}}</p>
            <p class="weather">
              {{weather}}
              <span>{{temperature}}</span>
            </p>
            <p class="winddirection">{{winddirection}}</p>
          </div>
        </div>
        <calendar
          :class="showCalendar?'':'hide_right'"
          class="right"
          weeks-type="en"
          cell-size="20"
          :header="showHeader"
          show-more-days="true"
          calendar-style="demo4-calendar"
          board-style="demo4-board"
          :days-color="demo4_days_style"
          @dayClick="dayClick"
        />
      </div>
      <image
        v-if="showPost"
        class="post_mood"
        :src="assetsUrl+'static/images/post_mood.png'"
        @tap="postMood"
      />
      <ul class="list">
        <li class="item" v-for="(item, index) in diaryList" :key="item._id" @tap="toDetail(item)">
          <image
            class="like"
            :src="assetsUrl+'static/images/like_active.png'"
            v-if="likeList[index] === '2'"
            @tap.stop="toLike(item._id, '1', item.like,index)"
          />
          <image
            class="like"
            :src="assetsUrl+'static/images/like.png'"
            v-if="likeList[index] === '1'"
            @tap.stop="toLike(item._id, '2', item.like,index)"
          />
          <image class="img" :src="item.url" mode="aspectFill" />
          <p class="desc">{{item.desc}}</p>
          <div class="name-weather">
            <span class="name">{{item.name}}</span>
            <span class="weather">{{item.weather}}</span>
          </div>
          <p class="time-address">
            <span class="time">{{item.time}}</span>
            <!-- <span class="address">{{item.address}}</span> -->
          </p>
        </li>
        <aLoadMore :status="status" mode="loading1" color="#333"></aLoadMore>
      </ul>
      <div class="loading-container" v-if="getSrcFlag">
        <aLoading mode="loading2"></aLoading>
      </div>
      <div class="dialog" v-if="showDialog">
        <div class="box">
          <h3>提示</h3>
          <p>是否授权使用点赞功能？</p>
          <div class="bottom">
            <button class="cancel" @tap="hideDialog">取消</button>
            <button class="confirm" lang="zh_CN" open-type="getUserInfo" @getuserinfo="login">确认</button>
          </div>
        </div>
      </div>
      <div class="fixed-to-top" @tap="goTop" :hidden='showTop'><image  :src="assetsUrl+'static/images/backtop1.png'" /></div>
      <div id="login" @touchstart="createLoves" @touchend="removeSmallHert">
        <background ref="background"></background>
       </div>
    </zrf>
  </cnlw>
</template>

<script>
// import global from '@/components/global';
import aLoading from '@/components/loading';
import aLoadMore from "@/components/loadup";
import background from '@/components/background';
import amapFile from "@/common/js/amap-wx.js";
import tools from "@/common/js/tools";
export default {
  name: "Index",
  components: {aLoading,aLoadMore,background},
  data() {
    return {
      assetsUrl:this.globalData.assetsUrl||'https://6365-ceart-d4onv-1301709499.tcb.qcloud.la/',
      showTop:true,//返回顶部
      state: "",
      z_state:999,
      status:'down',
      animations: false,
      pageInex:1,
      pageSize:6,
      total:0,
      totalPage:0,
      isPlay: true,
      audioCtx: "",
      audioUrl:"",
      showCalendar: true,
      openId: "",
      showPost: false,
      showHeader: false,
      days_count: new Date(
        new Date().getFullYear(),
        new Date().getMonth() + 1,
        0
      ).getDate(),
      demo4_days_style: [],
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
      address: "",
      weather: "",
      temperature: "",
      winddirection: "",
      diaryList: [],
      likeList: [],
      showDialog: false,
      userInfo: null,
      tempObj: null,
      getSrcFlag: true
    };
  },
  onLoad: function(){
    const that = this;
    wx.showNavigationBarLoading();
    that.setCalendarStyle();//日历
    that.audioCtx = wx.createAudioContext("myAudio");
    wx.setStorageSync('audioCtx',that.audioCtx);
    that.getOpenId();
  },
  onShow: function(){
    const that = this;
    that.isPlay = true;
    that.getWeather();//天气
    that.getMusicUrl();//音乐
  },

  onHide: function() {
   },

  onPageScroll(e) {//监听滚动
    // console.log(e.scrollTop)
    if (e.scrollTop>300) {
      this.showTop=false;
    } else {
      this.showTop=true;
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.pageInex=1;
    this.getDiaryList();
    wx.showNavigationBarLoading();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.totalPage > this.pageInex) {
      this.pageInex= this.pageInex+ 1;
      wx.showNavigationBarLoading();
      this.getDiaryList();
    } else {
      wx.showToast({
        title: '没有更多数据了！',
        icon: 'none',
        duration: 2000
      })
    };
  },

  methods: {
    createLoves(event){
    	this.$refs.background.createLoves(event)
    },
    removeSmallHert(){
    	this.$refs.background.removeSmallHert()
    },
    audioPlay() {//音乐播放
      const that = this;
      if (that.isPlay) {
        that.audioCtx.pause();
        that.isPlay = !that.isPlay;
        tools.showToast("您已暂停音乐播放~");
      } else {
        that.audioCtx.play();
        that.isPlay = !that.isPlay;
        tools.showToast("背景音乐已开启~");
      }
      wx.setStorageSync('audioCtx',that.audioCtx);
    },

    getMusicUrl() {//音乐
      const that = this;
      wx.cloud
        .callFunction({
          name: "getMusic",
          data: {}
        })
        .then(res => {
          that.audioUrl = res.result.data[0].musicUrl;
          that.audioCtx.loop = true;
          that.audioCtx.play();
        });
    },

    getOpenId() {
      const that = this;
      wx.cloud
        .callFunction({
          name: "user",
          data: {}
        })
        .then(res => {
          that.openId = res.result.openid;
          if (that.openId === "oQUZ45Ixc6vBdKsWxgQkw94QSqs8" || that.openId === "oqsx85SodsinfPqcIt7b0Xe3i_Is") {
            that.showPost = true;
          }
          that.getDiaryList();
        });
    },

    setCalendarStyle() {//日历
      const that = this;
      for (let i = 1; i <= that.days_count; i++) {
        if (i === that.day) {
          that.demo4_days_style.push({
            month: "current",
            day: i,
            color: "white",
            background: "#46c4f3"
          });
        } else {
          that.demo4_days_style.push({
            month: "current",
            day: i,
            color: "#333"
          });
        }
      }
    },

    getWeather() {//天气
      const that = this;
      let myAmapFun = new amapFile.AMapWX({ key: tools.key });
      myAmapFun.getWeather({
        success(res) {
          // 成功回调
          that.address = res.liveData.city;
          that.weather = res.liveData.weather + " ";
          that.temperature = res.liveData.temperature + "℃";
          that.winddirection =
            res.liveData.winddirection + "风" + res.liveData.windpower + "级";
        },
        fail(info) {
          // 失败回调
          console.log(info);
        }
      });
    },

    dayClick(e) {
      let temp = e.mp.detail;
      console.log(temp)
      wx.showToast({
        title: "农历" + temp.lunarMonth + temp.lunarDay,
        icon: "none",
        duration: 1000
      });
    },

    getDiaryList() {//文章列表
      const that = this;
      that.getSrcFlag =true ;
      that.status='loading';
      wx.cloud
        .callFunction({
          name: "diaryList",
          data: {
            pageInex:this.pageInex,
            pageSize:this.pageSize
          }
        })
        .then(res => {
          that.getSrcFlag = false;
          that.state='close-view';

          that.likeList =this.pageInex == 1 ? []:that.likeList;
          res.result.list.forEach((item, index) => {
            item.like.forEach(itemSecond => {
              if (itemSecond.openId === that.openId) {
                that.likeList.push(itemSecond.type);
              }
            });
            if (that.likeList.length < index + 1) {
              that.likeList.push("1");
            }
          });
         // 判断是否拼接:分页加载
          that.diaryList= that.pageInex == 1 ? res.result.list : [...that.diaryList, ...res.result.list];
          if(that.pageInex == 1){
          wx.setNavigationBarTitle({
            title: `Ceart的小窝(${res.result.total}条)`,
          })
          }
          that.totalPage=res.result.totalPage||Math.ceil(Number(res.result.total) / that.pageSize);
          that.status=that.totalPage==that.pageInex?'normal':'down';
          wx.hideNavigationBarLoading();
          wx.hideLoading();
          wx.stopPullDownRefresh();
          setTimeout(function () {
             that.z_state=-1
          }, 2000)
        });
    },

    switchCalendar() {
      const that = this;
      that.showCalendar = !that.showCalendar;
    },

    postMood() {
      const that = this;
      wx.navigateTo({
        url:
          "/pages/postMood/main?address=" +
          that.address +
          "&openId=" +
          that.openId +
          "&weather=" +
          that.weather
      });
    },

    toDetail(obj) {
      // const that = this
      wx.navigateTo({
        url:
          "/pages/diaryDetail/main?name=" +
          obj.name +
          "&url=" +
          obj.url +
          "&desc=" +
          obj.desc +
          "&address=" +
          obj.address +
          "&likeList=" +
          JSON.stringify(obj.like)
      });
    },

    toLike(id, type, arr,index) {
      const that = this;
      that.tempObj = {
        id: id,
        type: type,
        like: arr
      };
      wx.getSetting({
        success(res) {
          if (res.authSetting["scope.userInfo"]) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function(res) {
                that.userInfo = res.userInfo;
                wx.cloud
                  .callFunction({
                    name: "like",
                    data: {
                      id: id,
                      type: type,
                      like: arr,
                      name: that.userInfo.nickName
                    }
                  })
                  .then(res => {
                    if (type === "1") {
                      tools.showToast("取消点赞成功");
                    } else {
                      tools.showToast("点赞成功~");
                    }
                    that.likeList[index]=type;
                    // that.getOpenId();
                  });
              }
            });
          } else {
            that.showDialog = true;
          }
        }
      });
    },

    hideDialog() {
      const that = this;
      that.showDialog = false;
    },

    goTop(){
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    },

    login(e) {
      const that = this;
      console.log(that.tempObj, e);
      if (e.target.errMsg === "getUserInfo:ok") {
        wx.getUserInfo({
          success: function(res) {
            that.userInfo = res.userInfo;
            wx.cloud
              .callFunction({
                name: "like",
                data: {
                  id: that.tempObj.id,
                  type: that.tempObj.type,
                  like: that.tempObj.like,
                  name: that.userInfo.nickName
                }
              })
              .then(res => {
                if (that.tempObj.type === "1") {
                  tools.showToast("取消点赞成功");
                } else {
                  tools.showToast("点赞成功~");
                }
                that.getOpenId();
              });
          }
        });
      }
      that.showDialog = false;
    }
  },
  onShareAppMessage: function(res) {//分享
    return {
      title: "CeartDiary",
      path: "/pages/index/main",
  		success: function success(res) {
  			console.log("转发成功", res);
  		},
  		fail: function fail(res) {
  			console.log("转发失败", res);
  		}
    };
  }
};
</script>

<style lang="stylus" scoped>
@-webkit-keyframes musicRotate
  from
    -webkit-transform rotate(0deg)
  to
    -webkit-transform rotate(360deg)

@-webkit-keyframes musicStop
  from
    -webkit-transform rotate(20deg)
  to
    -webkit-transform rotate(0deg)

@-webkit-keyframes musicStart
  from
    -webkit-transform rotate(0deg)
  to
    -webkit-transform rotate(20deg)

@-webkit-keyframes fromLeft
  from
    -webkit-transform translateX(-250rpx)
  to
    -webkit-transform translateX(0)

@-webkit-keyframes toLeft
  from
    -webkit-transform translateX(0)
  to
    -webkit-transform translateX(-250rpx)

@-webkit-keyframes fromRight
  from
    -webkit-transform translateX(500rpx)
  to
    -webkit-transform translateX(0)


@-webkit-keyframes toRight
  from
    -webkit-transform translateX(0)
  to
    -webkit-transform translateX(500rpx)

@-webkit-keyframes decreaseHeight
  from
    height 500rpx
  to
    height 80rpx

@-webkit-keyframes addHeight
  from
    height 80rpx
  to
    height 500rpx

/*透明度累增渐变 */
@-webkit-keyframes fadeIn
  0%
    opacity 0.5
  30%
    opacity 0.8
  100%
    opacity 1

/* 透明度渐渐的消失 */
@-webkit-keyframes topImage
  0%
    top 0rpx
    left 0rpx
    opacity 0.9
  30%
    opacity 0.6
  100%
    top -100%
    left -100%
    opacity 0

/* 底部图片透明度 */
@-webkit-keyframes bottomImage
  0%
    bottom 0rpx
    right 0rpx
    opacity 0.8
  100%
    bottom -100%
    right -100%
    opacity 0

 #login
 	position fixed
 	top 0
 	left 0
  height 100%
 	width 100%
  z-index 1

.loading-container
  position fixed
  width 100%
  height 100%
  top 0
  bottom 0
  left 0
  right 0
  // background #fff
  margin auto
  display flex
  justify-content center
  align-items center
  z-index 9999

.fixed-to-top
  position fixed
  left 30rpx
  bottom 30rpx
  z-index 999
  image
    height 83rpx
    width 89rpx
.index
  height 100%
  position relative

  /* 图片视图容器 */
  .animation-image
    position fixed
    top 0rpx
    left 0rpx
    width 100%
    height 100%
    z-index 999
    /* 顶部倒影图 */
    .top-image
      width 100%
      height 100%
      position absolute
      top 0rpx
      left 0rpx
      z-index 1
      animation fadeIn ease-out 0.2s forwards
    /* 底部图片背景 */
    .bottom-image
      width 100%
      height 100%
      position absolute
      bottom 0rpx
      right 0rpx
      z-index 2
      animation fadeIn ease-out 0.2s forwards
  .close-view
    .top-image
      animation topImage ease-in 1.5s both
    .bottom-image
      animation bottomImage ease-in 1.5s both

  .bg_music
    position fixed
    right 0
    top 20rpx
    width 100rpx
    z-index 99
    display flex
    justify-content flex-start
    align-items flex-start

    .musicImg
      width 60rpx
      height 60rpx

    .music_icon
      animation musicRotate 3s linear infinite

    .music_play
      width 28rpx
      height 60rpx
      margin-left -10rpx
      transform-origin top
      -webkit-transform rotate(20deg)
    .playImg
      animation musicStop 1s linear forwards
    .pauseImg
      animation musicStart 1s linear forwards
  #myAudio
    display none
  .calendar_box
    display flex
    justify-content space-around
    align-items center
    position relative
    min-height 80rpx
    background -webkit-linear-gradient(#66cdcc 0%, #ffffff 100%)

    .btn
      position absolute
      width 60rpx
      height 60rpx
      left 30rpx
      top 10rpx
      z-index 99

    .left
      flex 1
      display flex
      flex-direction column
      justify-content center
      align-items center
      padding-top 80rpx

      .circle
        height 160rpx
        width 160rpx
        border-radius 100rpx
        background #ED758D
        margin 0 auto 30rpx
        display flex
        flex-direction column
        justify-content center
        align-items center

        .day
          color #fff
          font-size 30rpx

        .month
          color #e6e6e6
          font-size 50rpx

      .addressWeather
        height 200rpx
        width 100%
        display flex
        flex-direction column
        justify-content center
        align-items center

        .address
          text-align: center;
          font-size: 40rpx;
          margin-bottom: 20rpx;
          color: #1296db;

        .weather
          text-align: center;
          font-size: 50rpx;
          color: #63A92C;
          margin-bottom: 20rpx;

          span
            color: #F86635;


        .winddirection
          text-align: center;
          font-size: 30rpx;
          color: #773917;

    .hide_left
      animation: toLeft 0.3s linear forwards;


    .right
      flex: 2;
      padding-top: 80rpx;


    .hide_right
      animation: toRight 0.3s linear forwards;


  .hide_box
    animation: decreaseHeight 0.05s linear forwards;
    -webkit-animation-delay: 0.3s;

  .post_mood
    position fixed
    right 30rpx
    bottom 30rpx
    height 100rpx
    width 100rpx
    box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1)
    border-radius 50%
    background #fff
    z-index 99

  .list
    width 690rpx
    padding 50rpx 30rpx
    display flex
    justify-content flex-start
    align-items flex-start
    flex-wrap wrap

    .item
      width 330rpx
      margin-right 30rpx

      &:nth-of-type(2n+0)
        margin-right 0

      display flex
      flex-direction column
      justify-content flex-start
      align-items flex-start
      box-shadow 0 0 20rpx rgba(0, 0, 0, 0.1)
      margin-bottom 40rpx
      padding-bottom 30rpx
      border-radius 0 0 16rpx 16rpx
      position: relative
      z-index 9
      .like
        position: absolute;
        right: 10rpx;
        top: 10rpx;
        z-index: 9;
        background: #fff;
        height: 30rpx;
        width: 30rpx;
        padding: 0;
        margin: 0;
        border-radius: 50%;
        padding: 10rpx;

      .img
        width: 100%;
        height: 180rpx;
        margin-bottom: 20rpx;
        border-radius: 16rpx 16rpx 0 0;


      .desc
        line-height: 60rpx;
        height: 60rpx;
        color: #333;
        padding-left: 20rpx;
        width: 290rpx;
        word-wrap: break-word;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 30rpx;


      .name-weather
        height: 50rpx;
        line-height: 50rpx;
        color: #66cdcc;
        font-size: 24rpx;
        padding-left: 20rpx;
        display: flex;
        width: 290rpx;
        justify-content: space-between;
        align-items: center;

        .weather
          color: #63A92C;

      .time-address
        height 40rpx
        line-height: 40rpx;
        color: #773917;
        font-size: 24rpx;
        padding-left: 20rpx;
        display: flex;
        width: 290rpx;
        justify-content: space-between;
        align-items: center;

        .address
          color: #999;

  .dialog
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 99;
    display: flex;
    justify-content: center;
    align-items: center;

    .box
      width: 500rpx;
      height: 240rpx;
      background: #fff;
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;

      h3
        height: 80rpx;
        line-height: 80rpx;
        font-size: 30rpx;
        color: #333;
        font-weight: 600;


      p
        height: 50rpx;
        line-height: 50rpx;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 30rpx;


      .bottom
        height: 80rpx;
        width: 100%;
        display: flex;
        justify-content: space-around;
        align-items: center;

        button
          color #333
          width 500rpx
          font-size 30rpx
          height 80rpx
          line-height 80rpx
          font-weight 600
          background #fff

          &:after
            border none
        .confirm
          color #63A92C
</style>
